import {
	requestURL,
	userInfoStorage
} from "@/common/utils/config.js";
import stringify from "@/common/request/querystring.js";
import {
	getToken
} from '@/common/api/user_api.js'
import store from '@/store/store.js'

let baseURL = requestURL;

//获取token
function getStorageToken() {
	// return uni.getStorageSync('userInfoClientUser').token;
	return uni.getStorageSync('ttToken');

}
// 请求完成时处理结果
function result(res, resolve, reject, options) {
	// uni.hideLoading()
	if (res && res != "") {
		let statusCode = res.statusCode;
		if (statusCode == 500) {
      console.log(res, resolve, reject, options,'=====res, resolve, reject, option')
			showToast('服务器出错了')
      if(options && options.throwErr){
        reject()
      }
		} else if (statusCode == 401) {
			//token解析出现得相关异常
			refreshToken(options, resolve)
		} else {
			let result; //请求结果
			let code = ""; //请求结果中的code
			if (typeof(res.data) == 'string') {
				//返回的结果为string,转换为对象
				try {
					result = JSON.parse(res.data);
				}catch{
          result = res.data;
        }
			} else {
				result = res.data;
			}
			if (result.code) {
				code = result.code;
			}
			switch (code) {
				case 401:
					//可能因非法操作出现401时可酌情根据url判断处理
					break
				case 501:
				// case 500:
        case 1011009:
        
				case 1011006:
					//token过期或失效时
					if (isRefreshing) {
						resolve(res.data)
					} else {
						refreshToken(options, resolve)
					}
					break
				default:
					resolve(res)
					break
			}
		}

	}
}

let requestArr = [],
	isRefreshing = false; //请求队列，是否正在刷新token
//刷新toekn
function refreshToken(options, resolve) {
  if(uni.getStorageSync('isFromEshopLink')){
    return false
  }
  
	// let userInfo = uni.getStorageSync('userInfoClientUser');
	//如果为get请求会在请求地址后面拼接参数，此判断防止token不匹配二次请求参数重复拼接的问题
	if (options && options.params) {
		options.params = null
	}
	requestArr.push(() => {
		resolve(requestSecond(options))
	}); //缓存请求到队列中
	if (!isRefreshing) {
		isRefreshing = true;
    uni.login({
      async success(res) {
        getToken({
          code:res.code
        }).then(res => {
          if (res.data.code == 200) {
            uni.setStorageSync('ttToken', res.data.data)
            // userInfo.token = res.data;
            // store.commit('user/setUserInfo', userInfo);
            // 重新请求队列
            requestArr.map(MT => {
              MT();
            });
          } else {
            let adClick = uni.getStorageSync('adClickId')
            uni.clearStorageSync()
            uni.setStorageSync('adClickId',adClick)
            uni.reLaunch({
              url: '/pages/index/index'
            });
          }
          requestArr = []; //清空队列
        }).finally(() => {
          //解除正在刷新
          isRefreshing = false;
          console.log('结束了')
        });
      },
      fail(){
        
      },
    })
		
	}
}



//发送请求
function requestSecond(options = {}) {
	return new Promise((resolve, reject) => {
    // const isHideLoading = uni.getStorageSync('isHideLoading')
    // if(!isHideLoading){
    //   uni.showLoading()
    // }
		
		//判断dataType不存在或为空则设置为json格式
		if (!options.dataType) {
			options.dataType = 'json'
		}

		//判断参数不存在或为空则设置为空对象
		if (options.params) {
			options.url += '?' + stringify(options.params)
		}

		//请求头
		const header = {
			"ClientType": 'psychology',
			'Content-Type': "application/json;charset=UTF-8",
			...options.header,
		}
    



		if (getStorageToken()) {
			header['Authorization'] = "Bearer " + getStorageToken();
		}
		baseURL = requestURL;
		console.log(baseURL + options.url, '>>>>>请求路径')
    console.log(options,'>>>>>options')
		if (options.data) {
			console.log(JSON.stringify(options.data), '>>>>>请求参数' + options.url)
		}
		uni.request({
			url: baseURL + options.url,
			data: options.data,
			method: options.method || 'post',
			header: header,
			dataType: options.dataType,
			success: (res) => {
				console.log(res, '>>>>>响应实体' + options.url)
				result(res, resolve, reject, options.opts)
			},
			fail: (err) => {
				console.log(err, '>>>>>响应实体' + options.url)
				let errMsg = "";
				if (err != undefined && err.errMsg != undefined) {
					errMsg = err.errMsg;
				}
				showToast("连接失败：服务器出错:" + errMsg);
				reject();
			}
		});
	})

}

function request(data, url, method,opts) {
	if (method == 'POST') {
		return requestSecond({
			url: url,
			method: 'POST',
			data: data,
      opts
		}).then(res => res)
	} else {
		return requestSecond({
			url: url,
			method: 'GET',
			params: data
		}).then(res => res)
	}
}


//提示信息
export function showToast(title, position = "center", icon = "none", duration = 2000) {
	uni.showToast({
		title,
		position,
		icon,
		duration
	});
}

export default request